using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data.Contexts;

namespace UniversalAdmin.Infrastructure.Repositories;

public class ChatHistoryRepository : Repository<ChatHistory>, IChatHistoryRepository
{
    public ChatHistoryRepository(ApplicationDbContext context) : base(context)
    {
    }

    public async Task<(IEnumerable<ChatHistory> Histories, int TotalCount)> GetPagedByUserIdAsync(Guid userId, int page, int pageSize)
    {
        var query = _context.ChatHistories
            .Where(ch => ch.UserId == userId)
            .AsQueryable();

        var totalCount = await query.CountAsync();
        var histories = await query
            .OrderByDescending(ch => ch.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        return (histories, totalCount);
    }

    public async Task<IEnumerable<ChatHistory>> GetBySessionIdAsync(Guid sessionId)
    {
        return await _context.ChatHistories
            .Where(ch => ch.SessionId == sessionId)
            .OrderBy(ch => ch.CreatedAt)
            .ToListAsync();
    }

    public async Task<IEnumerable<ChatHistory>> GetRecentAsync(Guid userId, int count = 10)
    {
        return await _context.ChatHistories
            .Where(ch => ch.UserId == userId)
            .OrderByDescending(ch => ch.CreatedAt)
            .Take(count)
            .ToListAsync();
    }

    public async Task<(IEnumerable<ChatHistory> Histories, int TotalCount)> SearchAsync(Guid userId, string keyword, int page, int pageSize)
    {
        var query = _context.ChatHistories
            .Where(ch =>
                ch.UserId == userId &&
                (ch.Question.Contains(keyword) || ch.Answer.Contains(keyword)))
            .AsQueryable();

        var totalCount = await query.CountAsync();
        var histories = await query
            .OrderByDescending(ch => ch.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        return (histories, totalCount);
    }

    public async Task DeleteBySessionIdAsync(Guid sessionId)
    {
        var histories = await _context.ChatHistories
            .Where(ch => ch.SessionId == sessionId)
            .ToListAsync();

        _context.ChatHistories.RemoveRange(histories);
        await _context.SaveChangesAsync();
    }

    public async Task<int> GetSessionCountAsync(Guid userId)
    {
        return await _context.ChatHistories
            .Where(ch => ch.UserId == userId)
            .Select(ch => ch.SessionId)
            .Distinct()
            .CountAsync();
    }
}